﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Dts.Runtime;
using System.ServiceModel;
using Zen4SyncOrchestratorServices;

namespace Zen4SyncSSISComponent
{
    [DtsTask(DisplayName = "Zen4Sync Start Test Session Task", Description = "Allows to start a Zen4Sync Test Session given its ID", TaskType = "DTS100")]
    public class LoadTestSessionTask : Task
    {
        #region - Properties -

        /// <summary>
        /// ID of the Test Session to start.
        /// </summary>
        public string TestSessionId { get; set; }

        /// <summary>
        /// Zen4Sync password used by the Orchestrator to decrypt encrypted data.
        /// </summary>
        public string Zen4SyncSymmetricKeyPassword { get; set; }

        #endregion - Properties -

        #region - Methods -

        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            try
            {
                ChannelFactory<IOrchestratorServices> client = new ChannelFactory<IOrchestratorServices>("Config");

                IOrchestratorServices orchestrator = client.CreateChannel();
                orchestrator.StartTestSession(new Guid(TestSessionId), Zen4SyncSymmetricKeyPassword);

                client.Close();
                return DTSExecResult.Success;
            }
            catch (Exception)
            {
                return DTSExecResult.Failure;
            }
        }

        public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log)
        {
            // Allow an empty value since this method is also called when the user drops the Task on the Design surface.
            if (string.IsNullOrEmpty(TestSessionId))
                return DTSExecResult.Success;

            try
            {
                Guid guid = new Guid(TestSessionId);
                return DTSExecResult.Success;
            }
            catch
            {
                return DTSExecResult.Failure;
            }
        }

        #endregion - Methods -
    }
}

